package com.tnl.hunter.webchat.controller;

import com.biz.hunter.dao.CityDAO;
import com.biz.hunter.dao.EmployerDAO;
import com.biz.hunter.dao.SchDicDAO;
import com.biz.hunter.dao.WXUserDAO;
import com.biz.hunter.db.entity.*;
import com.biz.system.config.WebchatServiceConstant;
import com.biz.wechat.annotation.OAuthRequired;
import com.biz.wechat.util.SignUtil;
import com.tnl.hunter.dto.ErrorMsg;
import com.tnl.hunter.webchat.service.SchJobService;
import com.tnl.hunter.webchat.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("wechat/hunter/school/schJob")
public class SchJobController {
	private static final Logger logger = LoggerFactory.getLogger(SchJobController.class);
	@Autowired
	private SchJobService schJobService;
	@Autowired
	private SysConfigRepo sysConfigService;
	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private EmployerDAO employerDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private SchDicDAO schDicDAO;

	@OAuthRequired
	@RequestMapping("/add")
	public String toAddView(HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
//		openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		logger.debug("openid is " + openid);
		if (StringUtils.isEmpty(openid)) {
			logger.debug("openid is null");
			return "wechat/headhunter/errorpage";
		}
		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid " + openid + " is not subscribed");
			return "wechat/headhunter/errorpage";
		}
		// 获取自己的信息，HR是一个employer
		Employer employer = employerDAO.getByOpenId(openid);
		List<City> cities = cityDAO.getALL();
		List<SchDic> spec = schDicDAO.getAll("spec");
		List<SchDic> school = schDicDAO.getAll("school");
		model.addAttribute("specs",spec);
		model.addAttribute("schools",school);
		model.addAttribute("createBy",String.valueOf(employer.getId()));
		model.addAttribute("cities",cities);
		model.addAttribute("model","create");

		String ticket = sysConfigService.getJsTicket();
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);

		return "wechat/headhunter/school/createJob";
	}
	@OAuthRequired
	@RequestMapping("/editView")
	public String toEditView(String id, HttpServletRequest request, Model model) {
		SchJob job = schJobService.getById(id);
		List<City> cities = cityDAO.getALL();
		model.addAttribute("job", job);
		model.addAttribute("cities",cities);

		String ticket = sysConfigService.getJsTicket();
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);

		return "wechat/headhunter/school/createJob";
	}

	@RequestMapping("/saveJob")
	@ResponseBody
	public ErrorMsg save(@RequestBody SchJob schJob) {
		schJobService.addJob(schJob);
		ErrorMsg msg = new ErrorMsg();
		msg.setErrorcode("0");
		msg.setMsg("发布成功");
		msg.setData(1);
		return msg;
	}

	@RequestMapping("/get")
	public String getJobById(String id,HttpServletRequest request, Model model) {
		SchJob byId = schJobService.getById(id);
		List<City> cities = cityDAO.getALL();
		List<SchDic> spec = schDicDAO.getAll("spec");
		List<SchDic> school = schDicDAO.getAll("school");
		model.addAttribute("specs",spec);
		model.addAttribute("schools",school);
		model.addAttribute("job",byId);
		model.addAttribute("cities",cities);
		model.addAttribute("model","edit");

		String ticket = sysConfigService.getJsTicket();
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);

		return "wechat/headhunter/school/createJob";
	}

	@RequestMapping("/editJob")
	@ResponseBody
	public ErrorMsg editSchJob(@RequestBody SchJob schjob) {
		schJobService.updateJob(schjob);
		ErrorMsg msg = new ErrorMsg();
		msg.setErrorcode("0");
		msg.setMsg("更新成功");
		msg.setData(1);
		return msg;
	}
	@OAuthRequired
	@RequestMapping("/del/{id}")
	public void delSchJob(@PathVariable("id") String id,HttpServletResponse response) {
		schJobService.delete(id);
	}

	@OAuthRequired
	@RequestMapping("/page")
	@ResponseBody
	public ErrorMsg moreData( SchJob schjob, HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
//		openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		logger.debug("openid is " + openid);

		// 获取自己的信息，HR是一个employer
		Employer employer = employerDAO.getByOpenId(openid);
		if (employer != null) {
			schjob.setCreateBy(String.valueOf(employer.getId()));

		}

		int offset = 0;
		String startStr = request.getParameter("offset");
		if (StringUtils.isEmpty(startStr)) {
			offset = 0;
		} else {
			offset = Integer.valueOf(startStr);
		}
		List<SchJob> list =  schJobService.page(offset,10,schjob);
		list.forEach(j -> {
			String s = DateUtils.formatDate(j.getCreateTime(), "yyyy-MM-dd");
			j.setCreateDateStr(s);
			switch (j.getDegree()) {
				case 1 :
					j.setSpecialtyName("本科"); break;
				case 2 :
					j.setSpecialtyName("硕士"); break;
				case 3 :
					j.setSpecialtyName("博士"); break;
				case 4 :
					j.setSpecialtyName("博士后"); break;
			}
		});
		model.addAttribute("joblist", list);

		ErrorMsg msg = new ErrorMsg();
		msg.setErrorcode("0");
		msg.setMsg("获取数据成功");
		msg.setData(list);
		return msg;
	}

	@OAuthRequired
	@RequestMapping("/list")
	public String jobList( SchJob schjob, HttpServletRequest request, Model model) {
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute("OpenId");
//		openid = "o852IsxjLjGA0kmPlF0bQ2suht0Y";
		logger.debug("openid is " + openid);
		if (StringUtils.isEmpty(openid)) {
			logger.debug("openid is null");
			return "wechat/headhunter/errorpage";
		}
		UserInfo user = userDAO.getByOpenId(openid);
		if (user == null) {
			logger.info("the openid " + openid + " is not subscribed");
			return "wechat/headhunter/errorpage";
		}
		// 获取自己的信息，HR是一个employer
		Employer employer = employerDAO.getByOpenId(openid);
		if (employer == null) {
			/*
			 * Employer newItem = new Employer(); newItem.setOpenid(openid); model.addAttribute("employer", newItem); return
			 * "wechat/headhunter/hr/hrxinxi1";
			 */
			model.addAttribute("title", "温馨提示");
			model.addAttribute("msg", "你尚未注册我们的平台，请点击下方按钮前往注册。");
			model.addAttribute("url", "wechat/employer/main.page");
			return "wechat/headhunter/msgpage";
		} else {
			if (employer.getBinded() != 1) {
				model.addAttribute("title", "信息审核中");
				model.addAttribute("msg", "您的信息正在认证审核中，审核通过后会有短信通知您，请您耐心等待。如有疑问请添加我们的客服微信（ID:ElenaYu807）咨询。");
				return "wechat/headhunter/msgpage";
			}
			schjob.setCreateBy(String.valueOf(employer.getId()));
		}

		List<SchJob> list =  schJobService.page(0,100,schjob);
		list.forEach(j -> {
			j.setCompanyName(employer.getCompanyName());
			String s = DateUtils.formatDate(j.getCreateTime(), "yyyy-MM-dd");
			j.setCreateDateStr(s);
			j.setDescription("");
			switch (j.getDegree()) {
				case 1 :
					j.setSpecialtyName("本科"); break;
				case 2 :
					j.setSpecialtyName("硕士"); break;
				case 3 :
					j.setSpecialtyName("博士"); break;
				case 4 :
					j.setSpecialtyName("博士后"); break;
			}
			String[] arr = j.getCityId().split(",");
			if (!StringUtils.isEmpty(arr)) {
				String cityName = "";
				for (String cityId : arr) {
					City city = cityDAO.getById(Integer.valueOf(cityId));
					if (city != null) {
						cityName += city.getName();
						cityName += ",";
					}
				}
				j.setCityName(cityName.substring(0,cityName.length()-1));
			}
		});
		model.addAttribute("joblist", list);

		String ticket = sysConfigService.getJsTicket();
		String url = request.getRequestURL().toString();
		if (!StringUtils.isEmpty(request.getQueryString())) {
			url = url + "?" + request.getQueryString();
		}
		Map<String, String> jsconfig = SignUtil.getJSSignature(ticket, url);
		jsConfig config = new jsConfig();
		config.setAppid(WebchatServiceConstant.APPID);
		config.setCurrenttimestamp(jsconfig.get("timestamp"));
		config.setNonceStr(jsconfig.get("nonceStr"));
		config.setSignatureStr(jsconfig.get("signature"));
		model.addAttribute("config", config);

		return "wechat/headhunter/school/jobList";
	}
}
